<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-divider v-if="isRecommend">为你推荐</van-divider>
      <!-- 商品列表 -->
      <div class="goods">
        <goodsitem
          v-for="item in goodslist"
          :key="item.id"
          id="goodslist"
          :describe="item.title"
          :price="item.market_price"
          :buy="item.buy"
          :url="item.img_url"
          @click.native="$router.push(`/particulars/${item.id}`)"
        ></goodsitem>
      </div>
      <van-divider v-if="isLoadDone || !isRecommend">已经全部加载</van-divider>
    </van-pull-refresh>
  </div>
</template>

<script>
import _ from "lodash";
import { reqRecommend } from "@/api";
import goodsitem from "@/component/GoodsItem.vue";
export default {
  components: {
    goodsitem,
  },
  data() {
    return {
      goodslist: [],
      page: 1,
      pagesize: 10,
      isLoadDone: false,
      count: 0,
      isLoading: false,
      isRecommend: true,
    };
  },
  methods: {
    onRefresh() {
      setTimeout(async () => {
        this.$toast("刷新成功");
        this.isLoading = false;
        this.count++;
        this.page++;
        let { message } = await reqRecommend(this.page, this.pagesize);
        if (message.length === 0) {
          this.$toast("没有更多");
          this.isRecommend = false;
        }
        this.goodslist = message;
      }, 1000);
    },

    async getGoodsList() {
      let { message } = await reqRecommend(this.page, this.pagesize);
      this.goodslist = message;
    },

    async loadGoodsList() {
      // 加载完成就不再触发滚动事件，不再触发请求
      if (this.isLoadDone) {
        return;
      }
      //滚上去的高度
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //   网页视口的宽度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //整个页面的高度
      let pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

      if (Math.ceil(scrollTop) + windowHeight === pageHeight) {
        this.page++;
        let { message } = await reqRecommend(this.page, this.pagesize);
        // this.isLoadDone = false;
        if (message.length === 0) {
          // 说明数据加载完毕了
          this.isLoadDone = true;
          return;
        }
        this.goodslist = [...this.goodslist, ...message];
      }
    },
  },
  // 节流
  created() {
    this.throttleLoadGoodsList = _.throttle(this.loadGoodsList, 300);
  },
  async mounted() {
    // 加载商品列表数据
    this.getGoodsList();
    // 给窗口绑定滚动事件
    window.addEventListener("scroll", this.throttleLoadGoodsList);
  },
  // eslint-disable-next-line vue/no-deprecated-destroyed-lifecycle
  beforeDestroy() {
    window.removeEventListener("scroll", this.throttleLoadGoodsList);
  },
};
</script>

<style lang="scss" scoped>
.goods {
  display: flex;
  flex-wrap: wrap;
  // justify-content: center;
  padding: 5px;

  #goodslist {
    margin: 5px;
  }
}

.van-divider {
  border-color: #c3c5c8;
}
</style>
